//
//  YZEMyBasicinfoViewController.m
//  yilutongxing
//
//  Created by T&J on 2017/3/23.
//  Copyright © 2017年 YZE. All rights reserved.
//

#import "CommonDefine.h"
#import "NSString+PinYin.h"
#import "YZEMyBasicinfoViewController.h"
#import <ActionSheetCustomPicker.h>
#import <ActionSheetDatePicker.h>
#import <MJExtension.h>
#import <QMUITips.h>
#import <GTMBase64.h>
#import "RPUserInfoBean.h"
#import "UserDefaultsTools.h"
#import "IQActionSheetPickerView.h"
#import "DataUtils.h"
#import "PYSearchViewController.h"
#import "RPHospitalInfo.h"

#define GraftingsURL @"/api/graftings"
#define URL_DistrictsTree @"/api/districtsTree"
#define URL_SearchHospital @"/api/_search/hospitals?query=" //搜索医院接口
#define URL_SuggestionHospital @"/api/commonhospitals?page=0&size=10000" //搜索医院界面中的建议数据接口

@interface YZEMyBasicinfoViewController () <NetworkUtilsDelegate,PYSearchViewControllerDelegate, PYSearchViewControllerDataSource,
                                            YZEMyBasicinfoValueSetter,ActionSheetCustomPickerDelegate,IQActionSheetPickerViewDelegate,
                                            UINavigationControllerDelegate, UIImagePickerControllerDelegate>
@property (strong, nonatomic) IBOutlet UITableViewCell *hospital_cell;

@property (nonatomic,strong) NSArray *cityArr; // 解析出来的最外层数组
@property (nonatomic,strong) NSArray *provinceArr; // 省
@property (nonatomic,strong) NSArray *countryArr; // 市
@property (nonatomic,strong) NSArray *districtArr; // 区
@property (nonatomic,strong) NSMutableArray *districtArr1;
@property (nonatomic,assign) long districtID;
@property (nonatomic,strong) NSMutableArray *districtIDArr;
@property (nonatomic,assign) NSInteger index1; // 省下标
@property (nonatomic,assign) NSInteger index2; // 市下标
@property (nonatomic,assign) NSInteger index3; // 区下标
@property (nonatomic,strong) ActionSheetCustomPicker *city_picker; // 选择器
@property (nonatomic, strong) ActionSheetDatePicker *date_picker;
@property(nonatomic,strong)RPUserInfoBean *bean;
@property(nonatomic,strong)UIImageView *_avatar_img;
@property(nonatomic,strong)NSMutableArray *array;

//医院搜索相关
@property (nonatomic, strong) NSArray *commonHospitalArr;//常用医院
@property (nonatomic, retain) NSArray *hospitalArr;//所有医院
@property (nonatomic, retain) NSMutableArray *tobeChoosenArr;//备选医院
@property (nonatomic, retain) NSMutableArray *sortedHospitalArr;//整理好的医院名称数组
@property (nonatomic, assign) BOOL isSearched;//搜索状态

@property (nonatomic, strong) NSMutableArray *grafthingArr;
@property (nonatomic, strong) NSMutableArray *grafthingIDArr;

@property (nonatomic, strong) NSMutableArray *hospitolArr;
@property (nonatomic, strong) NSMutableArray *hospitolIDArr;

@property(nonatomic,strong)UIImage *tempImage;
@property(nonatomic,copy)NSString *avatarPath;
@end

@implementation YZEMyBasicinfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationController.navigationBarHidden = NO;
    self.navigationItem.title = @"我的资料";
    
    [[YZENetwork sharedInstace]getRequestWithUrl:[BASE stringByAppendingString:URL_DistrictsTree] parameters:nil delegate:self requestTag:1 successBlock:^(id responseObject) {
        self.array=responseObject;
        // 一定要先加载出这三个数组，不然就蹦了
        [self calculateFirstData];
        
    }];
    

    self.grafthingArr=[NSMutableArray array];
    self.grafthingIDArr=[NSMutableArray array];
    self.hospitolArr=[NSMutableArray array];
    self.hospitolIDArr=[NSMutableArray array];
    
    //获取所有移植类型
    [[YZENetwork sharedInstace]getRequestWithUrl:[BASE stringByAppendingString:GraftingsURL] parameters:nil delegate:self requestTag:1 successBlock:^(id responseObject) {
        NSArray *arr = [BaseModel mj_keyValuesArrayWithObjectArrayAdd:responseObject];
        for (NSDictionary *base in arr) {
            [self.grafthingArr addObject:base[@"name"]];
            [self.grafthingIDArr addObject:base[@"id"]];
        }
        
    }];
    
    dispatch_async(GLOBAL_BG_QUEUE, ^{
        [self getHostpitalData];
    });

    
    //设置头像
    self._avatar_img = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"avatar.jpg"]];
    self._avatar_img.frame = CGRectMake(SCREEN_WIDTH-94, 8, 64, 64);
    self._avatar_img.layer.masksToBounds=YES;
    self._avatar_img.layer.cornerRadius=32;
    [self.avatar.contentView addSubview:self._avatar_img];

    
    //设置选择器
    if (self.selections.count) {
        self.index1 = [self.selections[0] integerValue];
        self.index2 = [self.selections[1] integerValue];
        self.index3 = [self.selections[2] integerValue];
    }
    
    
    NSDictionary *dic =[UserDefaultsTools getUserDefaultsForKey:USERINFO_KEY];
    self.bean=[RPUserInfoBean mj_objectWithKeyValues:dic];
    if (!self.bean) {
        self.bean = [RPUserInfoBean new];
        self.bean.province = [RPUserInfoProvinceBean new];
        self.bean.city = [RPUserInfoCityBean new];
        self.bean.district = [RPUserinfoDistrictBean new];
        self.bean.grafting = [NSMutableDictionary dictionary];
        self.bean.hospital = [NSMutableDictionary dictionary];
    }
    
    [self._avatar_img sd_setImageWithURL:[NSURL URLWithString:self.bean.avatar]];
    self.name.detailTextLabel.text=self.bean.user.firstName?self.bean.user.firstName:@" ";
    self.shoushu_type.detailTextLabel.text=self.bean.grafting[@"name"]?self.bean.grafting[@"name"]:@"其它类型";
    self.gender.detailTextLabel.text=[self.bean.gender isEqualToString:@"MALE"]?@"男":@"女";
    self.birthdate.detailTextLabel.text=self.bean.birthday?self.bean.birthday:@" ";
    self.shoushu_hospital.detailTextLabel.text=self.bean.hospital[@"name"]?self.bean.hospital[@"name"]:@" ";
    self.patient_hisbook_no.detailTextLabel.text=self.bean.casenumber?self.bean.casenumber:@" ";
    self.patient_id_no.detailTextLabel.text=self.bean.medicalnumber?self.bean.medicalnumber:@" ";
    NSString *area;
    if ([self.bean.district.city.province.name isEqualToString:self.bean.district.city.name]) {
        area = [NSString stringWithFormat:@"%@%@", self.bean.district.city.province.name, self.bean.district.name];
    }
    else {
        area = [NSString stringWithFormat:@"%@%@%@", self.bean.district.city.province.name, self.bean.district.city.name, self.bean.district.name];
    }
    self.area.detailTextLabel.text=area;
    self.address.detailTextLabel.text=self.bean.address?self.bean.address:@" ";
 
    
    
    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(saveClick)];

}

-(void)saveClick{
    //[UserDefaultsTools saveUserDefaultsObject:self.bean.mj_keyValues forKey:USERINFO_KEY];
    NSMutableDictionary *pto=[NSMutableDictionary dictionary];
    //处理头像
    if (self.tempImage) {
        if ([self.delegate respondsToSelector:@selector(backHeadImage:)]) {
            [self.delegate backHeadImage:self.tempImage];
        }
        NSData *raw_data = UIImageJPEGRepresentation(self.tempImage, 1.0f);
        NSData *encoded_data = [GTMBase64 encodeData:raw_data];
        NSString *str = [[NSString alloc]initWithData:encoded_data encoding:NSASCIIStringEncoding];
        pto[@"avatar"]=str;
    }
    else {
        NSData *raw_data = UIImageJPEGRepresentation(self._avatar_img.image, 1.0f);
        NSData *encoded_data = [GTMBase64 encodeData:raw_data];
        NSString *str = [[NSString alloc]initWithData:encoded_data encoding:NSASCIIStringEncoding];
        pto[@"avatar"] = str;
    }
    pto[@"name"]=self.name.detailTextLabel.text;
    pto[@"gender"]=[self.gender.detailTextLabel.text isEqualToString:@"男"]?@"MALE":@"FEMALE";
    pto[@"grafting"]=@{@"id":self.bean.grafting[@"id"]};
    pto[@"hospitalDTO"]=@{@"id":self.bean.hospital[@"id"]};
    pto[@"birthday"]=self.birthdate.detailTextLabel.text;
    pto[@"casenumber"]=self.patient_hisbook_no.detailTextLabel.text;
    pto[@"medicalnumber"]=self.patient_id_no.detailTextLabel.text;
    pto[@"district"]=@{@"id":[NSNumber numberWithLong:self.bean.district.id]};
    pto[@"address"]=self.address.detailTextLabel.text;
    pto[@"phone"]=self.bean.phone;

    [[YZENetwork sharedInstace] postRequestWithUrl:URL_UserInfo parameters:pto delegate:self requestTag:1 successBlock:^(id responseObject) {
        [QMUITips hideAllToastInView:self.view animated:YES];
        [QMUITips showInfo:@"保存成功" inView:self.view hideAfterDelay:2];
        [self.navigationController popViewControllerAnimated:YES];
    }];
    [QMUITips showLoading:@"正在保存" inView:self.view];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    id ipage = segue.destinationViewController;
    [ipage setValue:self forKey:@"delegate"];
    if ([segue.identifier compare:@"TFInput"]==NO) {
        UITableViewCell *c = sender;
        [ipage setValue:^(NSString *text){
            c.detailTextLabel.text = text;
        } forKey:@"block"];
        [ipage setValue:@"name" forKey:@"pn"];
    }
}

//设置信息
- (void)setKeyValue:(NSString *)keyname valuename:(NSString *)val{
    NSMutableDictionary *ctrls = [[NSMutableDictionary alloc] initWithObjectsAndKeys:self.bean.user.firstName, @"name",
                                  self.patient_hisbook_no,@"hisbook_no",
                                  self.patient_id_no,@"patientcard_no",
                                  self.address,@"address", nil];
    UITableViewCell *c = ctrls[keyname];
    c.detailTextLabel.text = val;
    if ([keyname isEqualToString:@"name"]) {
        self.bean.user.firstName = val;
    }
    else if ([keyname isEqualToString:@"hisbook_no"]) {
        self.bean.casenumber = val;
    }
    else if([keyname isEqualToString:@"patientcard_no"]){
        self.bean.medicalnumber = val;
    }
    else if([keyname isEqualToString:@"address"]){
        self.bean.address = val;
    }
}

#pragma mark - Table view data source
//返回table节数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    //warning Incomplete implementation, return the number of sections
    return 1;
}
//返回table某节的行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    //warning Incomplete implementation, return the number of rows
    return 10;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    self.current_cell_index = indexPath;
    UITableViewCell *c = [tableView cellForRowAtIndexPath:indexPath];
    if (!c) {
        return;
    }
    //选择地区
    if ([c.restorationIdentifier compare:@"cell_area"]==NO) {
        self.city_picker = [[ActionSheetCustomPicker alloc]initWithTitle:@"选择地区" delegate:self showCancelButton:YES origin:self.view initialSelections:@[@(self.index1),@(self.index2),@(self.index3)]];
        self.city_picker.tapDismissAction  = TapActionSuccess;
        // 可以自定义左边和右边的按钮
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        button.frame = CGRectMake(0, 0, 44, 44);
        [button setTitle:@"取消" forState:UIControlStateNormal];
        
        UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
        [button1 setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        button1.frame = CGRectMake(0, 0, 44, 44);
        [button1 setTitle:@"确定" forState:UIControlStateNormal];
        [self.city_picker setCancelButton:[[UIBarButtonItem alloc] initWithCustomView:button]];
        [self.city_picker setDoneButton:[[UIBarButtonItem alloc] initWithCustomView:button1]];
        
        [self.city_picker showActionSheetPicker];
        
    }
    //选择头像
    else if ([c.restorationIdentifier compare:@"cell_avatar"]==NO){
        UIImagePickerController *vc = [UIImagePickerController new];
        vc.delegate = self;
        vc.allowsEditing = YES;
        [self presentViewController:vc animated:YES completion:nil];
    }
    //选择生日
    else if([c.restorationIdentifier compare:@"cell_birthdate"]==NO){
        self.date_picker = [ActionSheetDatePicker showPickerWithTitle:@"选择日期" datePickerMode:UIDatePickerModeDate selectedDate:[NSDate date] minimumDate:[NSDate dateWithTimeIntervalSinceNow:-100*12*30*24*3600] maximumDate:[NSDate dateWithTimeIntervalSinceNow:0] doneBlock:^(ActionSheetDatePicker *picker, id selectedDate, id origin) {
            NSDate *date = selectedDate;
            NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
            fmt.dateFormat = [NSString stringWithFormat:@"yyyy-MM-dd"];
            NSString *datestr = [fmt stringFromDate:date];
            NSLog(@"date:%@", datestr);
            c.detailTextLabel.text = datestr;
        } cancelBlock:nil origin:self.view];
    }
    //选择性别
    else if([c.restorationIdentifier compare:@"cell_gender"]==NO){
        UIAlertController *Alert=[UIAlertController alertControllerWithTitle:@"请选择性别" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        
        UIAlertAction *action1=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        UIAlertAction  *action2=[UIAlertAction actionWithTitle:@"男" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            self.gender.detailTextLabel.text=@"男";
            [self.tableView reloadData];
        }];
        UIAlertAction *action3=[UIAlertAction actionWithTitle:@"女" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            self.gender.detailTextLabel.text=@"女";
            [self.tableView reloadData];
        }];
        //3.将按键添加到警告框中
        [Alert addAction:action1];
        [Alert addAction:action2];
        [Alert addAction:action3];
        
        //将警告呈现处理
        [self presentViewController:Alert animated:YES completion:nil];
        
    }
    //选择移植类型
    else if([c.restorationIdentifier compare:@"cell_shoushu_type"]==NO){
        IQActionSheetPickerView *picker = [[IQActionSheetPickerView alloc] initWithTitle:@"" delegate:self];
        picker.titleFont = [UIFont systemFontOfSize:12];
        picker.titleColor = [UIColor redColor];
        [picker setTag:1];
        [picker setTitlesForComponents:@[self.grafthingArr]];
        [picker show];
    }
    //选择医院
    else if([c.restorationIdentifier compare:@"cell_shoushu_hospital"]==NO){
        [self goSearchHospital];
    }
    
}

//加载城市json
- (void)loadFirstData
{
    self.cityArr = [[NSArray alloc]initWithContentsOfFile:[[DataUtils getDocumentsPath] stringByAppendingPathComponent:DISTRICTREE_PLISTNAME]];
    NSMutableArray *firstName = [[NSMutableArray alloc] init];
    for (NSDictionary *dict in self.cityArr)
    {
        NSString *name = dict[@"provinceName"];
        [firstName addObject:name];
    }
    // 第一层是省份 分解出整个省份数组
    self.provinceArr = firstName;
}

// 根据传进来的下标数组计算对应的三个数组
- (void)calculateFirstData
{
    // 拿出省的数组
    [self loadFirstData];
    
    NSMutableArray *cityNameArr = [[NSMutableArray alloc] init];
    // 根据省的index1，默认是0，拿出对应省下面的市
    for (NSDictionary *cityName in self.cityArr[self.index1][@"citys"]) {
        
        NSString *name1 = cityName[@"cityName"];
        [cityNameArr addObject:name1];
    }
    // 组装对应省下面的市
    self.countryArr = cityNameArr;
    // index1对应省的字典         市的数组 index2市的字典   对应市的数组
    self.districtArr = self.cityArr[self.index1][@"citys"][self.index2][@"districts"];
    [self.districtArr1 removeAllObjects];
    [self.districtIDArr removeAllObjects];
    for (NSDictionary *dic in self.districtArr) {
        [self.districtArr1 addObject:dic[@"districtName"]];
        [self.districtIDArr addObject:dic[@"districtID"]];
    }
}

#pragma mark - UIPickerViewDataSource Implementation
//返回pickerview列数
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 3;
}
//返回pickerview某列行数
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    // Returns
    switch (component)
    {
        case 0: return self.provinceArr.count;
        case 1: return self.countryArr.count;
        case 2:return self.districtArr1.count;
        default:break;
    }
    return 0;
}

//点击头像进入相册事件

#pragma mark 选择图片
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    UIImage *image = info[UIImagePickerControllerEditedImage];
    self._avatar_img.image=image;
    self.tempImage=image;
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
    return YES;
}

-(BOOL)shouldAutorotate
{
    return YES;
}


-(void)actionSheetPickerView:(IQActionSheetPickerView *)pickerView didSelectTitles:(NSArray *)titles
{
    
    switch (pickerView.tag)
    {
        case 1:
            self.shoushu_type.detailTextLabel.text=[titles componentsJoinedByString:@""];
            [self.bean.grafting setObject:self.shoushu_type.detailTextLabel.text forKey:@"name"];
            NSInteger idIndex = [self.grafthingArr indexOfObject:self.shoushu_type.detailTextLabel.text];
            [self.bean.grafting setObject:[NSNumber numberWithLong:(long)[self.grafthingIDArr[idIndex] longLongValue]]
                                                           forKey:@"id"];
            
            break;
            
        case 3:
            self.shoushu_hospital.detailTextLabel.text=[titles componentsJoinedByString:@""];
            [self.bean.hospital setObject:self.shoushu_hospital.detailTextLabel.text forKey:@"name"];
            NSString *hospitolID=self.hospitolIDArr[[self.hospitolArr indexOfObject:self.shoushu_hospital.detailTextLabel.text]];
            [self.bean.hospital setObject:[NSNumber numberWithLong:(long)[hospitolID longLongValue]] forKey:@"id"];
            break;
            
    }
    [self.tableView reloadData];
}

#pragma mark 医院搜索相关
//获取所有医院
- (void)getHostpitalData{
    [[YZENetwork sharedInstace]getRequestWithUrl:[BASE stringByAppendingString:URL_SuggestionHospital] parameters:nil delegate:self requestTag:3 successBlock:^(id responseObject) {
        self.commonHospitalArr = [RPHospitalInfo mj_objectArrayWithKeyValuesArrayAdd:responseObject[@"common"]];
        self.hospitalArr = [RPHospitalInfo mj_objectArrayWithKeyValuesArrayAdd:responseObject[@"all"]];
        NSMutableArray *tempAll = [self.hospitalArr mutableCopy];
        //整理数据
        //1.取 广东 和 广州 开头的
        NSMutableArray *guangArr = [NSMutableArray array];
        NSEnumerator *en = [tempAll reverseObjectEnumerator];
        RPHospitalInfo *h1;
        while (h1 = [en nextObject]) {
            if ([h1.name rangeOfString:@"广东"].location!=NSNotFound
                || [h1.name rangeOfString:@"广州"].location!=NSNotFound) {
                [guangArr addObject:h1.name];
                [tempAll removeObject:h1];//移除广字头医院
            }
        }
        NSMutableDictionary *dic1 = [NSMutableDictionary dictionary];
        dic1[@"firstLetter"] = @"广";
        dic1[@"content"] = guangArr;
        [self.sortedHospitalArr addObject:dic1];
        //常用医院
        NSMutableArray *changArr = [NSMutableArray array];
        for (RPHospitalInfo *h2 in _commonHospitalArr) {
            [changArr addObject:h2.name];
        }
        NSMutableDictionary *dic2 = [NSMutableDictionary dictionary];
        dic2[@"firstLetter"] = @"常";
        dic2[@"content"] = changArr;
        [self.sortedHospitalArr addObject:dic2];
        //其它医院
        NSMutableArray *hospitalNameArr = [NSMutableArray array];
        for (RPHospitalInfo *h3 in tempAll) {
            [hospitalNameArr addObject:h3.name];
        }
        self.sortedHospitalArr  = [[hospitalNameArr arrayWithPinYinFirstLetterFormat] mutableCopy];
        [self.sortedHospitalArr insertObject:dic2 atIndex:0];
        [self.sortedHospitalArr insertObject:dic1 atIndex:0];
        self.isSearched = NO;
    }];
}

-(void)goSearchHospital{
    //创建控制器
    PYSearchViewController *searchViewController = [PYSearchViewController searchViewControllerWithHotSearches:nil searchBarPlaceholder:NSLocalizedString(@"搜索医院",@"搜索类型") didSearchBlock:^(PYSearchViewController *searchViewController, UISearchBar *searchBar, NSString *searchText) {
        for (RPHospitalInfo *hospital in self.hospitalArr) {
            if ([hospital.name isEqualToString:searchText]) {
                self.bean.hospital = [hospital mj_keyValues];
                self.hospital_cell.detailTextLabel.text = hospital.name;
            }
        }
        [searchViewController dismissViewControllerAnimated:YES completion:nil];
    }];
    //设置索引UI样式
    searchViewController.searchSuggestionView.sectionIndexColor = [UIColor colorWithRed:0.10 green:0.68 blue:0.94 alpha:1.0];
    searchViewController.searchSuggestionView.sectionIndexBackgroundColor= [UIColor clearColor];
    // 4. 设置代理
    searchViewController.delegate = self;
    searchViewController.dataSource = self;
    searchViewController.showSearchHistory = NO;
    [searchViewController setSearchSuggestionHidden:NO];
    searchViewController.cancelButton.tintColor = [UIColor colorWithRed:102/255.0 green:102/255.0 blue:102/255.0 alpha:1];
    searchViewController.cancelButton.title = @"取消";
    searchViewController.suggestionViewCellSeperatorStyle = UITableViewCellSeparatorStyleSingleLine;
    // 5. 跳转到搜索控制器
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:searchViewController];
    
    [self presentViewController:nav animated:YES completion:^{
        [searchViewController showSuggestionWhenLoaded];//加载即显示searchSuggestion
    }];
}

#pragma mark - PYSearchSuggestionViewDataSource
- (UITableViewCell*)searchSuggestionView:(UITableView *)searchSuggestionView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    if (_isSearched) {
        cell.textLabel.text = self.tobeChoosenArr[indexPath.row];
    }
    else {
        NSString *hospital;
        NSDictionary *dic = self.sortedHospitalArr[indexPath.section];
        NSArray *hospitalNameArr = dic[@"content"];
        hospital = hospitalNameArr[indexPath.row];
        cell.textLabel.text = hospital;
    }
    return cell;
}

- (NSInteger)searchSuggestionView:(UITableView *)searchSuggestionView numberOfRowsInSection:(NSInteger)section{
    if (_isSearched) {
        return [self.tobeChoosenArr count];
    }
    else {
        NSDictionary *dic = self.sortedHospitalArr[section];
        NSArray *hospitalNameArr = dic[@"content"];
        return [hospitalNameArr count];
    }
}

- (NSInteger)numberOfSectionsInSearchSuggestionView:(UITableView *)searchSuggestionView{
    if (_isSearched) {
        return 1;
    }
    else
        return [self.sortedHospitalArr count];
}

- (NSArray *)sectionIndexTitlesForSearchSuggestionView:(UITableView *)searchSuggestionView{
    NSMutableArray *titles = [NSMutableArray array];
    NSEnumerator *en = [self.sortedHospitalArr objectEnumerator];
    NSDictionary *dic;
    while (dic = [en nextObject]) {
        [titles addObject:dic[@"firstLetter"]];
    }
    return titles;
}

- (CGFloat)searchSuggestionView:(UITableView *)searchSuggestionView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 44;
}

- (CGFloat)searchSuggestionView:(UITableView *)searchSuggestionView heightForHeaderInSection:(NSInteger)section{
    return 30;
}

- (CGFloat)searchSuggestionView:(UITableView *)searchSuggestionView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}
/*
 - (NSString*)searchSuggestionView:(UITableView *)searchSuggestionView titleForHeaderInSection:(NSInteger)section{
 NSString *title = @" ";
 if (_isSearched) {
 title = @"搜索到如下结果";
 }
 else if([self.sortedHospitalArr count]>0){
 NSDictionary *dic = self.sortedHospitalArr[section];
 title = dic[@"firstLetter"];
 }
 return title;
 }
 */
- (UIView *)searchSuggestionView:(UITableView *)searchSuggestionView viewForHeaderInSection:(NSInteger)section{
    UIView *header = [[UIView alloc]initWithFrame:CGRectMake(0, 0, searchSuggestionView.frame.size.width, 30)];
    header.backgroundColor = COLOR_BG_GRAY;
    UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, header.width-10, header.height)];
    title.font = [UIFont systemFontOfSize:14];
    title.textAlignment = NSTextAlignmentLeft;
    title.textColor = BLACK_COLOR;
    
    if (_isSearched) {
        title.text = @"搜索到如下结果";
    }
    else if([self.sortedHospitalArr count]>0){
        NSDictionary *dic = self.sortedHospitalArr[section];
        title.text = dic[@"firstLetter"];
        if ([title.text rangeOfString:@"常"].location!=NSNotFound) {
            title.text = @"常用医院";
        }
    }
    [header addSubview:title];
    
    return header;
}

#pragma mark - PYSearchViewControllerDelegate
//在这里进行搜索操作
- (void)searchViewController:(PYSearchViewController *)searchViewController searchTextDidChange:(UISearchBar *)seachBar searchText:(NSString *)searchText
{
    if (searchText.length>0 && ![searchText isEqualToString:@" "]) {
        self.isSearched = YES;
        //后台线程搜索
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.tobeChoosenArr removeAllObjects];
            for (RPHospitalInfo *hospital in self.hospitalArr) {
                if ([hospital.name rangeOfString:searchText].location!=NSNotFound) {
                    [self.tobeChoosenArr addObject:hospital.name];
                }
            }
            [searchViewController.searchSuggestionView reloadData];
        });
    }
    else{
        self.isSearched = NO;
        [searchViewController.searchSuggestionView reloadData];
    }
}

#pragma mark UIPickerViewDelegate Implementation
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    switch (component)
    {
        case 0: return self.provinceArr[row];break;
        case 1: return self.countryArr[row];break;
        case 2:return self.districtArr1[row];break;
        default:break;
    }
    return nil;
}
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    UILabel* label = (UILabel*)view;
    if (!label)
    {
        label = [[UILabel alloc] init];
        [label setFont:[UIFont systemFontOfSize:14]];
    }
    
    NSString * title = @"";
    switch (component)
    {
        case 0: title =   self.provinceArr[row];break;
        case 1: title =   self.countryArr[row];break;
        case 2: title =   self.districtArr1[row];break;
        default:break;
    }
    label.textAlignment = NSTextAlignmentCenter;
    label.text=title;
    return label;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    switch (component)
    {
        case 0:
        {
            self.index1 = row;
            self.index2 = 0;
            self.index3 = 0;
            //            [self calculateData];
            // 滚动的时候都要进行一次数组的刷新
            [self calculateFirstData];
            [pickerView reloadComponent:1];
            [pickerView reloadComponent:2];
            [pickerView selectRow:0 inComponent:1 animated:YES];
            [pickerView selectRow:0 inComponent:2 animated:YES];
        }
            break;
            
        case 1:
        {
            self.index2 = row;
            self.index3 = 0;
            //            [self calculateData];
            [self calculateFirstData];
            [pickerView selectRow:0 inComponent:2 animated:YES];
            [pickerView reloadComponent:2];
        }
            break;
        case 2:
            self.index3 = row;
            break;
        default:break;
    }
}

- (void)configurePickerView:(UIPickerView *)pickerView
{
    pickerView.showsSelectionIndicator = NO;
}
// 点击done的时候回调
- (void)actionSheetPickerDidSucceed:(ActionSheetCustomPicker *)actionSheetPicker origin:(id)origin
{
    NSMutableString *detailAddress = [[NSMutableString alloc] init];
    if (self.index1 < self.provinceArr.count) {
        NSString *firstAddress = self.provinceArr[self.index1];
        [detailAddress appendString:firstAddress];
        self.bean.district.city.province.name = firstAddress;
    }
    if (self.index2 < self.countryArr.count) {
        NSString *secondAddress = self.countryArr[self.index2];
        [detailAddress appendString:secondAddress];
        self.bean.district.city.name = secondAddress;
    }
    if (self.index3 < self.districtArr1.count) {
        NSString *thirdAddress = self.districtArr1[self.index3];
        [detailAddress appendString:thirdAddress];
        self.bean.district.name = thirdAddress;
        self.bean.district.id=[self.districtIDArr[self.index3] longValue];
    }
    // 此界面显示
    UITableView *table = (UITableView*)self.view;
    UITableViewCell *c = [table cellForRowAtIndexPath:self.current_cell_index];
    c.detailTextLabel.text = detailAddress;
}

#pragma mark 数据配置
- (NSArray *)provinceArr
{
    if (_provinceArr == nil) {
        _provinceArr = [[NSArray alloc] init];
    }
    return _provinceArr;
}
-(NSArray *)countryArr
{
    if(_countryArr == nil)
    {
        _countryArr = [[NSArray alloc] init];
    }
    return _countryArr;
}

- (NSArray *)districtArr
{
    if (_districtArr == nil) {
        _districtArr = [[NSArray alloc] init];
    }
    return _districtArr;
}
- (NSMutableArray *)districtArr1
{
    if (_districtArr1 == nil) {
        _districtArr1 = [[NSMutableArray alloc] init];
    }
    return _districtArr1;
}
- (NSMutableArray *)districtIDArr
{
    if (_districtIDArr == nil) {
        _districtIDArr = [[NSMutableArray alloc] init];
    }
    return _districtIDArr;
}
-(NSArray *)cityArr
{
    if (_cityArr == nil) {
        _cityArr = [[NSArray alloc] init];
    }
    return _cityArr;
}
#pragma mark 网络代理回调
- (void)OnStartWithRequestTag:(int)tag{}
- (void)OnFinishWithRequestTag:(int)tag{}
- (void)OnSuccess:(id)responseObject requestTag:(int)tag{}
- (void)OnFail:(NSString *)errorMsg errorCode:(NSInteger)errorCode requestTag:(int)tag{
    [QMUITips hideAllToastInView:self.view animated:YES];
    [QMUITips showError:@"上传数据失败!" inView:self.view hideAfterDelay:1];
}
@end
